<template>
    <a-modal :keyboard="false" :maskClosable="false" title="流程编辑" :open="visible" :width="700" :confirmLoading="loading" centered @ok="handleSubmit" @cancel="handleCancel">
        <a-form layout="vertical">
            <a-row :gutter="16" type="flex" justify="start">
                <a-col :xs="24" :sm="24" :md="24">
                    <a-form-item label="流程名称" v-bind="validateInfos.name">
                        <a-input v-model:value="modelRef.name" />
                        <template #extra>注：请按照审批流程创建审批角色</template>
                    </a-form-item>
                </a-col>
                <a-col :xs="24" :sm="24" :md="24" v-for="(item, index) in modelRef.nodes" :key="index">
                    <a-form-item label="审批角色" v-bind="validateInfos.orderProfessionalLine" required>
                        <div class="flex nodes-item">
                            <a-select v-model:value="item.id" style="width: 100%" allow-search @change="val => handleChange(val, index)">
                                <a-select-option v-for="item in roleList" :key="item.id" :value="item.id">{{ item.name }}</a-select-option>
                            </a-select>
                            <minus-circle-outlined @click="handleMinus(index)" v-if="index > 0" />
                            <plus-outlined @click="handlePlus()" />
                        </div>
                    </a-form-item>
                </a-col>
                <div style="margin: 0 0 20px 10px">
                    <a-button v-if="isEmpty(modelRef.nodes)" @click="handlePlus">添加审批角色</a-button>
                </div>
                <a-col :xs="24" :sm="24" :md="24">
                    <a-form-item label="所属操作事项" v-bind="validateInfos.type">
                        <a-radio-group v-model:value="modelRef.type">
                            <a-radio v-for="(item, index) in options" :value="Number(item.value)" :key="index">{{ item.label }}</a-radio>
                        </a-radio-group>
                    </a-form-item>
                </a-col>
                <a-col :xs="24" :sm="24" :md="24">
                    <a-form-item label="流程状态" v-bind="validateInfos.state">
                        <a-radio-group v-model:value="modelRef.state">
                            <a-radio :value="1">启用</a-radio>
                            <a-radio :value="0">禁用</a-radio>
                        </a-radio-group>
                    </a-form-item>
                </a-col>
            </a-row>
        </a-form>
    </a-modal>
</template>

<script lang="ts">
    import type { PropType } from 'vue';
    import { PlusOutlined, MinusCircleOutlined } from '@ant-design/icons-vue';
    import { defineComponent, reactive, ref, watchEffect, watch } from 'vue';
    import { Form, message } from 'ant-design-vue';
    import { createProcess, updateProcess, getProcess } from '@/api/order/flow';
    import { cloneDeep, isEmpty, isUndefined } from 'lodash-es';
    import { getRolePage, getRoleAll } from '@/api/user/role';

    export default defineComponent({
        props: {
            visible: {
                type: Boolean,
                required: true,
            },
            model: {
                type: Object as PropType<any>,
                default: () => null,
            },
        },
        emits: ['cancel', 'success'],
        setup(props, { emit }) {
            const loading = ref(false);
            const options = [
                {
                    label: '强制关单',
                    value: 0,
                },
                {
                    label: '作废',
                    value: 1,
                },
                {
                    label: '投诉',
                    value: 2,
                },
                {
                    label: '任务暂停',
                    value: 3,
                },
                {
                    label: '巡检计划',
                    value: 5,
                },
            ];

            const roleList = ref<any[]>([]);
            const defaultForm = {
                status: 1,
                nodes: [
                    {
                        id: undefined,
                        name: '',
                    },
                ],
                name: '',
                type: '',
            };
            const modelRef = reactive<any>(cloneDeep(defaultForm));

            const rulesRef = reactive({
                name: [{ required: true, message: '请输入流程名称' }],
                type: [{ required: true, message: '请选择所属操作事项' }],
            });
            const { validateInfos, resetFields, validate } = Form.useForm(modelRef, rulesRef);

            // 记录初始值
            const initValues = reactive({});
            watch(
                () => props.visible,
                () => {
                    Object.assign(initValues, cloneDeep(props.model));
                },
            );
            watchEffect(() => {
                if (props.visible) {
                    getRoleAll({
                        size: 1000,
                        current: 1,
                    }).then(res => {
                        if (!isEmpty(res.data)) roleList.value = res.data;
                    });
                    console.log(props.model);

                    if (props.model) {
                        if (props.model.id)
                            getProcess(props.model.id).then(res => {
                                Object.assign(modelRef, props.model, {
                                    nodes: isEmpty(res.data.nodes) ? [] : JSON.parse(res.data.nodes),
                                });
                            });
                    }
                }
            });

            const handleChange = (val, index) => {
                console.log(val, index);
                const data = roleList.value.find(item => item.id === val);
                modelRef.nodes[index].id = val;
                modelRef.nodes[index].name = data.name;
            };

            const handlePlus = () => {
                modelRef.nodes.push({
                    id: undefined,
                    name: '',
                });
            };
            const handleMinus = index => {
                modelRef.nodes.splice(index, 1);
            };

            const handleCancel = () => {
                resetFields();
                Object.keys(modelRef).forEach(key => {
                    delete modelRef[key];
                });
                Object.assign(modelRef, cloneDeep(defaultForm));

                modelRef.state = 1;
                modelRef.nodes = [
                    {
                        id: undefined,
                        name: '',
                    },
                ];
                emit('cancel');
            };

            const handleSubmit = async () => {
                validate().then(() => {
                    loading.value = true;

                    (isUndefined(modelRef.id) ? createProcess : updateProcess)({
                        ...(modelRef as any),
                    })
                        .then(res => {
                            if (res.data) {
                                message.success('操作成功');
                                emit('success');
                                handleCancel();
                            }
                        })
                        .finally(() => {
                            loading.value = false;
                        });
                });
            };
            return {
                loading,

                modelRef,
                validateInfos,
                resetFields,

                handleSubmit,
                handleCancel,

                initValues,
                options,
                roleList,

                isEmpty,

                handleMinus,
                handlePlus,
                handleChange,
            };
        },
        components: {
            PlusOutlined,
            MinusCircleOutlined,
        },
    });
</script>

<style lang="less" scoped>
    .nodes-item {
        & > span {
            margin-left: 10px;
        }
    }
</style>
